package eic.dao.impl;

import eic.dao.ClientDAO;
import eic.entity.ClientEntity;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistryBuilder;

import java.util.List;

/**
 * Created by lzj on 2015/7/5.
 */
public class ClientImpl implements ClientDAO{

    SessionFactory sessionFactory = null ;
    Session session ;

    /**
     * 构造方法初始化sessionFactory
     */
    public ClientImpl(){
        ServiceRegistryBuilder srb = new ServiceRegistryBuilder();
        sessionFactory = new Configuration().configure().buildSessionFactory();
    }
    @Override
    public List<ClientEntity> getClients() {
        session = sessionFactory.openSession();
        ClientEntity entity=null;
        String sql="from ClientEntity";
        List list=session.createQuery(sql).list();
        return list;
    }

    @Override
    public boolean addClient(ClientEntity client) {
        session =sessionFactory.openSession();
        Transaction tx=session.beginTransaction();
        session.save(client);
        tx.commit();
        session.close();
        return  true;
    }

    @Override
    public boolean delClient(ClientEntity client) {
        session = sessionFactory.openSession();
        Transaction tx=session.beginTransaction();
        session.delete(client);
        tx.commit();
        session.close();
        return true;
    }

    @Override
    public boolean updClient(ClientEntity client) {
        session = sessionFactory.openSession();
        Transaction tx=session.beginTransaction();
        session.update(client);
        tx.commit();
        session.close();
        return true;
    }

    @Override
    public ClientEntity getClientById(int id) {
        session = sessionFactory.openSession();
        String hql="from ClientEntity client where client.id ="+id;
        ClientEntity client = new ClientEntity();
        client=(ClientEntity) session.createQuery(hql).uniqueResult();
        return client;
    }
}
